package tcards.android;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class YesNoField extends RelativeLayout {
	private RadioGroup mInput;
	private RadioButton mYes;
	private RadioButton mNo;
	private TextView mLabel;
	
	private void init(AttributeSet attrs) {
		TypedArray tArray = getContext().obtainStyledAttributes(attrs, R.styleable.Field);
		mInput = (RadioGroup) findViewById(R.id.yesnoInput);
		mYes = (RadioButton) findViewById(R.id.yesChoice);
		mNo = (RadioButton) findViewById(R.id.noChoice);
		mLabel = (TextView) findViewById(R.id.yesnoLabel);
		
		String text = tArray.getString(R.styleable.Field_label);
        if (text != null) { 
        	getLabel().setText(text + ":");
        }

		tArray.recycle();
	}	

	public YesNoField(Context context) {
		this(context, null, 0);
	}

	public YesNoField(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public YesNoField(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		LayoutInflater li = LayoutInflater.from(context);
		addView(li.inflate(R.layout.yesno_field, this, false));
		if (attrs != null) {
			init(attrs);
		}
	}

	public TextView getLabel() {
		return mLabel;
	}
	
	public RadioGroup getInput() {
		return mInput;
	}
	
	public Boolean getValue() {
		switch (mInput.getCheckedRadioButtonId()) {
		case R.id.yesChoice:
			return true;
		case R.id.noChoice:
			return false;
		default:
			return null;
		}
	}
	
	public void setValue(Boolean value) {
		if (value == null) {
			mYes.setChecked(false);
			mNo.setChecked(false);
		}
		else if (value) {
			mYes.setChecked(true);
			mNo.setChecked(false);
		}
		else {
			mYes.setChecked(false);
			mNo.setChecked(true);
		}
	}
}